package com.mobileClientKernel.android.serviceManager.network.requestexecutor;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BaseHttpStack;
import com.android.volley.toolbox.Volley;
import com.mobileClientKernel.android.serviceManager.network.IRequest;
import com.mobileClientKernel.android.serviceManager.network.JJBaseRequest;
import com.mobileClientKernel.android.serviceManager.volley.OkHttpStack;
import com.mobileClientKernel.android.commonLayer.JJLog;

import java.util.Map;

/**
 * Created by jj on 2018/5/10.
 */

public class VolleyExecutor implements IRequest {

    private static RequestQueue requestQueue = null;
    private static String LogModuleName = "VolleyExecutor";

    public VolleyExecutor(){
    }

    @Override
    public void executeRequest(JJBaseRequest request, int index, ResponseListener listener) {
        Context context = request.getContext();
        Map<String, String> map = request.requestArgument();
        String url = request.buildRequestUrl();

        int method = Request.Method.POST;
        switch (request.getRequestMethod()) {
            case Get: {
                method = Request.Method.GET;
            }
            break;

            case Delete: {
                method = Request.Method.DELETE;
            }
            break;

            case Put: {
                method = Request.Method.PUT;
            }
            break;

            case Patch: {
                method = Request.Method.PATCH;
            }
            break;

            case Head: {
                method = Request.Method.HEAD;
            }
            break;

        }

        VolleyRequest baseRequest = new VolleyRequest(index, method, url, map, listener, request);
        VolleyExecutor.getRequestQueue(context).add(baseRequest);
    }

    private static synchronized RequestQueue getRequestQueue(Context context) {
        if (requestQueue == null) {
            JJLog._i(LogModuleName, "get new request queue");
            requestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack());
        }
        return requestQueue;
    }
}
